package com.cloud.listener;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.cloud.common.constants.FlowTaskConstants;
import com.cloud.common.constants.GlobalConstants;
import com.cloud.utils.SecurityUtils;
import org.flowable.engine.impl.el.FixedValue;
import org.flowable.task.service.delegate.DelegateTask;
import org.flowable.task.service.delegate.TaskListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 表单信息保存任务监听器
 * FixedValue (定义名称与流程设计时字段名称一致)
 * com.cloud.listener.FormTaskListener
 */
@Component
public class FormTaskListener implements TaskListener {

    private static Logger logger = LoggerFactory.getLogger(FormTaskListener.class);

    // 表单对象保存地址
    private FixedValue requestUrl;

    // 节点表单Ket
    private FixedValue entityKey;

    @Override
    public void notify(DelegateTask delegateTask) {
        String nodeKey = null;
        try {
            Map<String, Object> variablesMap = delegateTask.getVariables();
            Object keyId = variablesMap.get(FlowTaskConstants.ENTITY_ID_CODE);
            if (Objects.isNull(keyId)) {
                keyId = delegateTask.getProcessInstanceId();
            }
            nodeKey = entityKey.getExpressionText();
            Object formObject = variablesMap.get(nodeKey);
            if (Objects.nonNull(formObject)) {
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json;charset=UTF-8");
                headers.put(GlobalConstants.appTokenHeader, SecurityUtils.getSysCode());
                headers.put(GlobalConstants.tokenHeader, SecurityUtils.getToken());
                // 包装请求表单参数
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put(FlowTaskConstants.PARAM_KET, keyId);
                paramMap.put(FlowTaskConstants.PARAM_VALUE, formObject);
                HttpRequest.post(requestUrl.getExpressionText())
                        .headerMap(headers, false).body(JSONObject.toJSONString(paramMap))
                        .timeout(60000).execute().body();
                logger.info("流程表单节点:[" + nodeKey + "]信息更新成功");
            }
        } catch (Exception e) {
            logger.info("流程表单节点:[" + nodeKey + "]信息更新失败");
        }
    }

}
